package com.ruin.tech.ahri.exception;

import com.ruin.tech.ahri.result.Result;
import com.ruin.tech.ahri.result.ResultCode;
import com.ruin.tech.ahri.result.ResultFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * @program ahri
 * @description: 全局异常捕获
 * @author: ruin
 * @create: 2019/11/20 17:05
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public ResponseEntity<Result> exceptionHandler(Exception e, HttpServletResponse servletResponse) {
        log.error("Exception:",e);
        Result result;
        HttpStatus status;
        if(e instanceof MethodArgumentNotValidException){
            status = HttpStatus.OK;
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException)e;
            result = ResultFactory.buildFailResult(ResultCode.PARAM_ERROR,exception.getBindingResult().getFieldError().getDefaultMessage());
        }else if(e instanceof HttpMessageNotReadableException){
            status = HttpStatus.OK;
            HttpMessageNotReadableException exception = (HttpMessageNotReadableException)e;
            result = ResultFactory.buildFailResult(ResultCode.PARAM_ERROR);
        }else if(e instanceof BizException){
            status = HttpStatus.OK;
            BizException exception = (BizException)e;
            result = ResultFactory.buildFailResult(ResultCode.FAIL,exception.getMessage());
        }else{
            status = HttpStatus.OK;
            result = ResultFactory.buildFailResult(ResultCode.FAIL);
        }

        return new ResponseEntity<>(result,status);
    }

}
